<?php

namespace app\admin\controller;

use app\admin\model\AdminLog;
use app\common\controller\Backend;
use think\Config;
use think\Hook;
use think\Validate;
use think\Db;

//入库相关
use app\admin\model\in\InInventory;
use app\admin\model\in\InInventoryDetail;
use app\admin\model\out\OutInventory;
use app\admin\model\out\OutInventoryDetail;
use app\admin\model\out\OutInventoryAddr;
use app\admin\model\in\InInbound;
use app\admin\model\in\InInboundDetail;
use app\admin\model\Inventory\InventoryItemInfo;
use app\admin\model\Item;
use app\admin\model\out\Test as OutOfStock;

/**
 * 后台首页
 * @internal
 */
class Index extends Backend
{

    protected $noNeedLogin = ['login'];
    protected $noNeedRight = ['index', 'logout'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
    }

    public function index_test(){
      
      for($i=0;$i<20000;$i++){
        $outInventory = new OutOfStock;   
        $inData = [];
        //保存出库记录
        $outOrderId = 'OUTI' . date('YmdHis') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $inData['orderstr'] = $outOrderId;
        // $inData[$this->dataLimitField] = $this->auth->aid;
        
        $outInventory->isUpdate(false)->save($inData);

      }
    }

    /**
     * 后台首页
     */
    public function index()
    {
        //左侧菜单
        list($menulist, $navlist, $fixedmenu, $referermenu) = $this->auth->getSidebar([
            'dashboard' => 'hot',
            'addon'     => ['new', 'red', 'badge'],
            'auth/rule' => __('Menu'),
            'general'   => ['new', 'purple'],
        ], $this->view->site['fixedpage']);
        $action = $this->request->request('action');
        if ($this->request->isPost()) {
            if ($action == 'refreshmenu') {
                $this->success('', null, ['menulist' => $menulist, 'navlist' => $navlist]);
            }
        }

        $this->view->assign('menulist', $menulist);
        $this->view->assign('navlist', $navlist);
        $this->view->assign('fixedmenu', $fixedmenu);
        $this->view->assign('referermenu', $referermenu);
        $this->view->assign('title', __('Home'));
        return $this->view->fetch();
    }

    /**
     * 管理员登录
     */
    public function login()
    {
        $url = $this->request->get('url', 'index/index');
        if ($this->auth->isLogin()) {
            $this->success(__("You've logged in, do not login again"), $url);
        }
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $keeplogin = $this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
                '__token__' => 'token',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                '__token__' => $token,
            ];
            if (Config::get('fastadmin.login_captcha')) {
                $rule['captcha'] = 'require|captcha';
                $data['captcha'] = $this->request->post('captcha');
            }
            $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            AdminLog::setTitle(__('Login'));
            $result = $this->auth->login($username, $password, $keeplogin ? 86400 : 0);
            if ($result === true) {
                Hook::listen("admin_login_after", $this->request);
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error($msg, $url, ['token' => $this->request->token()]);
            }
        }

        // 根据客户端的cookie,判断是否可以自动登录
        if ($this->auth->autologin()) {
            $this->redirect($url);
        }
        $background = Config::get('fastadmin.login_background');
        $background = stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background;
        $this->view->assign('background', $background);
        $this->view->assign('title', __('Login'));
        Hook::listen("admin_login_init", $this->request);
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        Hook::listen("admin_logout_after", $this->request);
        $this->redirect(url('index/login'));
    }

    /**
     * 同步入库数据
     *
     * @return void
     */
    public function insynch(){
      $inInventoryModel = new InInventory();
      $inInventoryItemInfoModel = new InventoryItemInfo();

      $inInventoryRecord = $inInventoryModel->where('1=1')->select();
      $itemModel = new Item();

      //入库单导入
      Db::startTrans();
      foreach($inInventoryRecord as $key=>$value){
        $inInventoryItemInfRecord = $inInventoryItemInfoModel->where('orderId',$value->inorderid)->select();

        foreach($inInventoryItemInfRecord as $detailkey=>$detailvalue){

          $inDetailModel = new InInventoryDetail;
          $detailData = [];
          $detailData['itemsku'] = $detailvalue->itemsku;
          $detailData['itemid'] = $itemModel->where('sku',$detailvalue->itemsku)->value('id');
          $detailData['itemname'] = $detailvalue->itemname;
          $detailData['goods_count'] = $detailvalue->instoragecount;
          $detailData['pw_count'] = 0;
          $detailData['left_count'] = $detailvalue->instoragecount;
          $detailData['goods_money'] = 0;
          $detailData['goods_price'] = 0;
          $detailData['inid'] = $detailvalue->id;
          $detailData['id'] = newId();
          $detailData['orderId'] = $value->inorderid;
          $detailData['warehouseid'] = '17A72FFA-B3F3-11E4-9DEA-782BCBD7746B';
          $detailData['warehouse_code'] = '1';
          $detailData['inBoxNo'] = '1';//入库的箱号
          $rsDetail = $inDetailModel->save($detailData);
        }
        // var_dump($value->inorderid);
      }
      Db::commit();
      echo('ok');

      // var_dump($inInventoryRecord);
      //创建入库单
      
      //确认入库
    }

    public function outsynch(){
      //出库的导入

      $outInventoryModel = new OutInventory();
      $outInventoryAddrModel = new OutInventoryAddr();
      $inInventoryItemInfoModel = new InventoryItemInfo();

      $outInventoryRecord = $outInventoryModel->where('1=1')->select();
      //出库单导入
      Db::startTrans();
      foreach($outInventoryRecord as $key=>$value){
        $outInventoryItemInfRecord = $inInventoryItemInfoModel->where('orderId',$value->outorderid)->select();
        $outInventoryAddrRecord = $outInventoryAddrModel->where('outorderid',$value->outorderid)->select()[0];

        foreach($outInventoryItemInfRecord as $detailkey=>$detailvalue){
          $outDetailModel = new OutInventoryDetail;

          $detailData = [];
          $detailData['id'] = \newId();
          $detailData['itemsku'] = $detailvalue->itemsku;

          $itemModel = new Item();

          $detailData['itemid'] = $itemModel->where('sku',$detailvalue->itemsku)->value('id');
          $detailData['itemname'] = $detailvalue->itemname;

          $detailData['orderid'] = $value->orderid;//关联的平台订单号

          $detailData['goods_count'] = $detailvalue->instoragecount; //申请出库数
          $detailData['sw_count'] = 0; //已出库数
          $detailData['left_count'] = $detailvalue->instoragecount; //未出库数

          $detailData['outid'] = $value->id;
          $detailData['out_orderno'] = $detailvalue->orderId;
          $detailData['warehouseid'] = '17A72FFA-B3F3-11E4-9DEA-782BCBD7746B';
          $detailData['warehouse_code'] = '1';
          $detailData['unique_no'] = $value->remark;

          $detailData['recipients']= $outInventoryAddrRecord->recipients;
          $detailData['mobile']= $outInventoryAddrRecord->mobile;
          $detailData['company']= $outInventoryAddrRecord->company;
          $detailData['state']= $outInventoryAddrRecord->state;
          $detailData['province']= $outInventoryAddrRecord->province;
          $detailData['city']= $outInventoryAddrRecord->city;
          $detailData['postcode']= $outInventoryAddrRecord->postcode;
          $detailData['addressone']= $outInventoryAddrRecord->addressone;
          $detailData['addresstwo']= $outInventoryAddrRecord->addresstwo;
          
          $rsDetail = $outDetailModel->save($detailData);

        }
        // var_dump($value->inorderid);
      }
      Db::commit();
      echo('ok');

      //创建出库单
      //确认出库

      // var_dump($inInventoryRecord);
    }

}
